package com.szhn.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.szhn.common.utils.JwtUtils;
import com.szhn.common.utils.MD5;
import com.szhn.userservice.entity.User;
import com.szhn.userservice.mapper.UserMapper;
import com.szhn.userservice.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-10-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public String login(User user) {
        String mobile = user.getMobile();
        String password = user.getPassword();  //获取到的是明文密码，而存到数据库中的是加密过的
        //使用和数据库存储密码一样的MD5加密【只能加密不能解密】
        String encrypt = MD5.encrypt(password);


        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        wrapper.eq("password", encrypt);
        User one = baseMapper.selectOne(wrapper);
        if (one == null) {
            return null;
        } else {
            //自己编写的根据id和名称生成token值
            String jwtToken = JwtUtils.getJwtToken(one.getId(), one.getNickname());

            return jwtToken;
        }
    }

    @Override
    public boolean register(User user) {
        //获取注册数据
        String mobile = user.getMobile();
        String nickname = user.getNickname();
        String password = user.getPassword();

        //判断参数是否为空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(password)) {
            return false;
        } else {
            //判断手机号是否重复
            Integer count = baseMapper.selectCount(new
                    QueryWrapper<User>().eq("mobile", mobile));
            if (count.intValue() > 0) {
                return false;
            } else {
                //添加注册信息到数据库
                User member = new User();
                member.setNickname(nickname);
                member.setMobile(mobile);
                member.setPassword(MD5.encrypt(password));
                boolean flag = this.save(member);
                return flag;
            }
        }
    }
}
